//
//  TravelInfoViewController.m
//  Community
//
//  Created by YaSha_Tom on 2018/12/21.
//  Copyright © 2018年 YaSha-Tom. All rights reserved.
//

#import "TravelInfoViewController.h"
#import "TravelTableViewCell.h"
#import "CommentsTableViewCell.h"
#import <ReactiveCocoa.h>
#import <objc/runtime.h>



@interface TravelInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIImageView *imageView;
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)NSArray *dataSource;
@property (nonatomic,strong)BmobObject *object;

@end

@implementation TravelInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"详情";
    self.view.backgroundColor = [UIColor whiteColor];
    [self initUI];
    [self createBttomView];
    [self doNetworking];
    //注册键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册键盘消失的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
}
- (void)initUI {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Width, Height-45) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];

}
- (void)createBttomView {
    NSLog(@"1");
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, Height-45, Width, 45)];
    //    imageView.backgroundColor = [UIColor blackColor];
    self.imageView.image = [UIImage imageNamed:@"toolbar_bottom_bar"];
    self.imageView.userInteractionEnabled = YES;
    [self.view addSubview:self.imageView];

    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 6,Width-75, 32)];
    self.textField.layer.cornerRadius = 6;
    self.textField.placeholder  = @"评论";
    self.textField.tag = 1001;
    self.textField.textAlignment = NSTextAlignmentLeft;
    self.textField.backgroundColor = [UIColor whiteColor];
    self.textField.delegate = self;
    [self.imageView addSubview:self.textField];
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setTitle:@"发送" forState:UIControlStateNormal];
    btn2.frame = CGRectMake(Width-60, -2, 60, 50);
    [btn2 addTarget:self action:@selector(sendMassage) forControlEvents:UIControlEventTouchUpInside];
    [self.imageView addSubview:btn2];
}
- (void)sendMassage {
    //在GameScore创建一条数据，如果当前没GameScore表，则会创建GameScore表
    BmobObject  *gameScore = [BmobObject objectWithClassName:@"remark"];
    [gameScore setObject:self.textField.text forKey:@"content"];
    NSUserDefaults *userdefaults =[NSUserDefaults standardUserDefaults];
    if (self.object) {
        [gameScore setObject: [NSString stringWithFormat:@"张三 回复 %@",[self.object objectForKey:@"name"]] forKey:@"name"];
        [gameScore setObject:[self.object objectForKey:@"id"] forKey:@"id"];
    }else{
        [gameScore setObject:@"张三" forKey:@"name"];
        [gameScore setObject:[self.obj objectForKey:@"objectId"] forKey:@"id"];
    }
    [gameScore setObject:[NSNumber numberWithBool:YES] forKey:@"isreply"];
    //异步保存到服务器
    [gameScore saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            //创建成功后会返回objectId，updatedAt，createdAt等信息
            //创建对象成功，打印对象值
            NSLog(@"%@",gameScore);
            self.textField.text = nil;
            [self doNetworking];
        } else if (error){
            //发生错误后的动作
            NSLog(@"%@",error);
        } else {
            NSLog(@"Unknow error");
        }
    }];
}
- (void)keyboardWasShown:(NSNotification*)aNotification{
    //键盘高度
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //表视图滚动至底部。
    [UIView animateWithDuration:0.5 animations:^{
        self.tableView.frame = CGRectMake(0, -keyBoardFrame.size.height, Width, Height-45);
        self.imageView.frame = CGRectMake(0,  Height-45-keyBoardFrame.size.height, Width, 45);
    }];
}

-(void)keyboardWillBeHidden:(NSNotification*)aNotification{
    self.imageView.frame = CGRectMake(0, Height-45, Width, 45);
    self.tableView.frame = CGRectMake(0, 0, Width, Height-45);
//    [_tableView reloadData];
    
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

#pragma mark - 单机窗口键盘隐藏
//说明：其实是选中到单元格了
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //直接调用隐藏键盘的方法即可
    [_textField resignFirstResponder];
}

#pragma mark - 滑动窗口时，键盘隐藏
- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    //直接调用隐藏键盘的方法即可
    [_textField resignFirstResponder];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else {
        return self.dataSource.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 30;

}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
   
    UIView *view = [[UIView alloc]init];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 345, 20)];
    if (section == 0) {
        lable.text = @"动态详情";
    }else {
        lable.text = @"评论记录";
    }
    [view addSubview:lable];
    return view;


}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        TravelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
            cell = [[TravelTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        [cell.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(Width/2, 20*rateh));
            make.right.mas_equalTo(cell.mas_right).offset(-15*rateh);
            make.top.mas_equalTo(cell.mas_top).offset(18);
            //        make.centerY.mas_equalTo(self.nameLabel);
        }];
        [cell setTravelData:self.obj];
        return cell;
    }else{
        CommentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
            cell = [[CommentsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        [cell.replyButton addTarget:self action:@selector(replyEvent:) forControlEvents:UIControlEventTouchUpInside];
        BmobObject *obj = self.dataSource[indexPath.row];
        objc_setAssociatedObject(cell.replyButton, "firstObject", obj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [cell setCommentsData:obj];
        return cell;
    }
}
- (void)replyEvent:(UIButton *)btn {
    [self.textField becomeFirstResponder];
  self.object = objc_getAssociatedObject(btn, "firstObject");

}

- (void)doNetworking {
    BmobQuery  *bquery = [BmobQuery queryWithClassName:@"remark"];
    //查找GameScore表的数据
    @weakify(self);
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        @strongify(self);
        self.dataSource = array;
        NSLog(@"------%lu",(unsigned long)self.dataSource.count);
        [self.tableView reloadData];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
